package com.hq.ims.platform.busservice;

import com.hq.ims.data.service.BaseBusiInfoService;
import com.hq.ims.data.service.BaseCompanyService;
import com.hq.ims.data.vo.statistics.statisticsEnum.EnumDimension;
import com.hq.ims.platform.vo.PlatformStatisticsMapstruct;
import com.hq.utils.util.BigDecimalUtil;
import com.hq.utils.util.LocalDateTimeUtils;
import com.hq.utils.util.StringUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 经营信息统计
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class PlatformStatisticsService {
    @Resource
    private BaseBusiInfoService baseBusiInfoService;
    @Resource
    private BaseCompanyService baseCompanyService;

    /**
     * 平台端企业发布和接收统计
     *
     * @param searchData 时间类型
     */
    public PlatformStatisticsMapstruct.CompanyBusiInfoCountStatisticsVo platformCompanyInfoStatistics(
            PlatformStatisticsMapstruct.CompanyStatisticsSearchData searchData
    ) {
        SpringBootValidateUtils.validate(searchData);
        //默认查所有
        List<String> childrenIdList = new ArrayList<>(0);
        if (StringUtils.isNotEmpty(searchData.getOrgId())) {
            //获取当前公司及以下的公司
//            childrenIdList = baseCompanyService.getChildrenIdList(searchData.getOrgId(), true);
            //查当指定公司
            childrenIdList = Arrays.asList(searchData.getOrgId());
        }

        LocalDateTime[] enumDimensionTimeInterval = this.getEnumDimensionTimeInterval(searchData.getDateType());
        LocalDateTime startDateTime = enumDimensionTimeInterval[0];
        LocalDateTime endDateTime = enumDimensionTimeInterval[1];
        //返回对象
        PlatformStatisticsMapstruct.CompanyBusiInfoCountStatisticsVo vo = new PlatformStatisticsMapstruct.CompanyBusiInfoCountStatisticsVo();
        //预生成日期
        List<String> dateStrList = this.generateStrDate(searchData.getDateType(), startDateTime, endDateTime);

        //----------------------- 作为发布方 数量线
        List<Map> companyStatisticsBusInfoPublishCountByDateTypeDataList = baseBusiInfoService.getBaseMapper().getPublisherFeedbackBusInfoCountByDateType(
                searchData.getDateType().name(), startDateTime, endDateTime, null, null
        );

        List<PlatformStatisticsMapstruct.DateAndCountVo> publishBusiInfoCountList = new ArrayList<>();
        vo.setPublishBusiInfoCountList(publishBusiInfoCountList);
        Map<String, PlatformStatisticsMapstruct.DateAndCountVo> publishBusiInfoMap = new HashMap<>();
        for (String dateStr : dateStrList) {
            PlatformStatisticsMapstruct.DateAndCountVo voObj = new PlatformStatisticsMapstruct.DateAndCountVo();
            publishBusiInfoCountList.add(voObj);
            publishBusiInfoMap.put(dateStr, voObj);

            voObj.setDateStr(dateStr);
            voObj.setCount(0);
        }

        for (Map map : companyStatisticsBusInfoPublishCountByDateTypeDataList) {
            String dateStr = map.get("dateStr").toString();
            PlatformStatisticsMapstruct.DateAndCountVo voObj = publishBusiInfoMap.get(dateStr);
            voObj.setCount(Integer.parseInt(map.get("count").toString()));
        }


        //----------------------- 作为接收方 数量线
        //数量统计
        List<Map> receiveFeedbackBusInfoCountByDateTypeMapList = baseBusiInfoService.getBaseMapper().getReceiveFeedbackBusInfoCountByDateType(
                searchData.getDateType().name(), startDateTime, endDateTime, childrenIdList, null
        );

        List<PlatformStatisticsMapstruct.DateAndCountVo> receiverBusiInfoCountList = new ArrayList<>();
        vo.setReceiveBusiInfoCountList(receiverBusiInfoCountList);
        Map<String, PlatformStatisticsMapstruct.DateAndCountVo> receiverBusiInfoCountMap = new HashMap<>();
        for (String dateStr : dateStrList) {
            PlatformStatisticsMapstruct.DateAndCountVo voObj = new PlatformStatisticsMapstruct.DateAndCountVo();
            receiverBusiInfoCountList.add(voObj);
            receiverBusiInfoCountMap.put(dateStr, voObj);

            voObj.setDateStr(dateStr);
            voObj.setCount(0);
        }

        //补全数据
        for (Map map : receiveFeedbackBusInfoCountByDateTypeMapList) {
            String dateStr = map.get("dateStr").toString();
            String countStr = map.getOrDefault("count", StringUtils.FH_ZERO).toString();
            PlatformStatisticsMapstruct.DateAndCountVo voObj = receiverBusiInfoCountMap.get(dateStr);
            voObj.setCount(Integer.parseInt(countStr));
        }

        //如果时间类型选择日,将日期改为MM-dd
        if(searchData.getDateType() == EnumDimension.Day){
            for (PlatformStatisticsMapstruct.DateAndCountVo publishBusiInfoCount : vo.getPublishBusiInfoCountList()) {
                publishBusiInfoCount.setDateStr(publishBusiInfoCount.getDateStr().substring(5));
            }

            for (PlatformStatisticsMapstruct.DateAndCountVo receiveBusiInfoCount: vo.getReceiveBusiInfoCountList()) {
                receiveBusiInfoCount.setDateStr(receiveBusiInfoCount.getDateStr().substring(5));
            }
        }

        return vo;
    }

    /**
     * 平台端企业收益统计(作为接收者)
     *
     * @param searchData 查询条件
     */
    public List<PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo> platformCompanyEarningsStatistics(
            PlatformStatisticsMapstruct.CompanyStatisticsSearchData searchData
    ) {
        SpringBootValidateUtils.validate(searchData);

        //默认查所有
        List<String> childrenIdList = new ArrayList<>(0);
        if (StringUtils.isNotEmpty(searchData.getOrgId())) {
            //获取当前公司及以下的公司
//            childrenIdList = baseCompanyService.getChildrenIdList(searchData.getOrgId(), true);
            //查当指定公司
            childrenIdList = Arrays.asList(searchData.getOrgId());
        }


        LocalDateTime[] enumDimensionTimeInterval = this.getEnumDimensionTimeInterval(searchData.getDateType());
        LocalDateTime startDateTime = enumDimensionTimeInterval[0];
        LocalDateTime endDateTime = enumDimensionTimeInterval[1];

        //金额统计
        List<Map> receiveFeedbackBusInfoMoneyByDateTypeMapList = baseBusiInfoService.getBaseMapper().getReceiveFeedbackBusInfoMoneyByDateType(
                searchData.getDateType().name(), startDateTime, endDateTime, childrenIdList, null
        );

        //获取时间
        //预生成日期
        List<String> dateStrList = this.generateStrDate(searchData.getDateType(), startDateTime, endDateTime);

        //初始化返回对象
        List<PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo> voList = new ArrayList<>();
        Map<String, PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo> receiveBusiInfoMap = new HashMap<>();
        for (String dateStr : dateStrList) {
            PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo voObj = new PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo();
            voList.add(voObj);
            receiveBusiInfoMap.put(dateStr, voObj);

            voObj.setDateStr(dateStr);
            voObj.setMoney(BigDecimal.ZERO);
        }

        //补全数据
        for (Map map : receiveFeedbackBusInfoMoneyByDateTypeMapList) {
            String dateStr = map.get("dateStr").toString();
            String moneyStr = map.getOrDefault("money", StringUtils.FH_ZERO).toString();
            PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo voObj = receiveBusiInfoMap.get(dateStr);
            voObj.setMoney(new BigDecimal(moneyStr));
        }

        //如果时间类型选择日,将日期改为MM-dd
        if(searchData.getDateType() == EnumDimension.Day){
            for (PlatformStatisticsMapstruct.CompanyEarningsMoneyStatisticsVo vo : voList) {
                vo.setDateStr(vo.getDateStr().substring(5));
            }
        }

        return voList;
    }

    /**
     * 平台端企业用户发布和接收统计
     *
     * @param searchData 时间类型
     */
    public List<PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo> platformCompanyUserEarningsDateStatistics(
            PlatformStatisticsMapstruct.CompanyUserStatisticsSearchData searchData
    ) {
        SpringBootValidateUtils.validate(searchData);
        //默认查所有
        String orgId = searchData.getOrgId();
        String userId = searchData.getUserId();

        LocalDateTime[] enumDimensionTimeInterval = this.getEnumDimensionTimeInterval(searchData.getDateType());
        LocalDateTime startDateTime = enumDimensionTimeInterval[0];
        LocalDateTime endDateTime = enumDimensionTimeInterval[1];
        //返回对象
        List<PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo> voList = new ArrayList<>();

        //----------------------- 作为接收方 反馈数量
        List<Map> companyStatisticsBusInfoPublishCountByDateTypeDataList = baseBusiInfoService.getBaseMapper().getUserReceiveFeedbackBusInfoCountByDateType(
                searchData.getDateType().name(), startDateTime, endDateTime, orgId, userId
        );
        Map<String, PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo> feedbackBusiInfoCountMap = new HashMap<>(companyStatisticsBusInfoPublishCountByDateTypeDataList.size());
        for (Map map : companyStatisticsBusInfoPublishCountByDateTypeDataList) {
            String forUserId = map.get("userId").toString();
            String forUserName = map.get("userName").toString();
            String countStr = map.getOrDefault("count", StringUtils.FH_ZERO).toString();

            PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo voObj = new PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo();
            voList.add(voObj);
            feedbackBusiInfoCountMap.put(forUserId, voObj);
            voObj.setUserId(forUserId);
            voObj.setUserName(forUserName);
            voObj.setCount(Integer.parseInt(countStr));
            voObj.setMoney(BigDecimal.ZERO);
        }


        //----------------------- 作为接收方 用户反馈为已投标金额
        //数量统计
        List<Map> receiveFeedbackBusInfoCountByDateTypeMapList = baseBusiInfoService.getBaseMapper().getUserReceiveFeedbackBusInfoMoneyByDateType(
                searchData.getDateType().name(), startDateTime, endDateTime, orgId, userId
        );

        for (Map map : receiveFeedbackBusInfoCountByDateTypeMapList) {
            String forUserId = map.get("userId").toString();
            String forUserName = map.get("userName").toString();
            String moneyStr = map.getOrDefault("money", StringUtils.FH_ZERO).toString();

            PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo voObj = feedbackBusiInfoCountMap.get(forUserId);
            if(voObj == null){
                voObj = new PlatformStatisticsMapstruct.UserBusiInfoCountStatisticsVo();
                voList.add(voObj);
                feedbackBusiInfoCountMap.put(forUserId, voObj);
                voObj.setUserId(forUserId);
                voObj.setUserName(forUserName);
                voObj.setCount(0);
            }
            voObj.setMoney(BigDecimalUtil.newBigDecimal(moneyStr));
        }
        return voList;
    }


    /**
     * 将日其进行填充
     *
     * @param dateType 时间类型
     */
    private List<String> generateStrDate(
            EnumDimension dateType,
            LocalDateTime startDateTime,
            LocalDateTime endDateTime
    ) {
        LocalDateTime dynamicStateStartDateTime = startDateTime;
        List<String> dateList = new ArrayList<>();
        while (dynamicStateStartDateTime.isBefore(endDateTime)) {
            switch (dateType) {
                case Day:
                    dateList.add(LocalDateTimeUtils.toStr(dynamicStateStartDateTime, "yyyy-MM-dd"));
                    dynamicStateStartDateTime = dynamicStateStartDateTime.plusDays(1);
                    break;
                case Month:
                    dateList.add(LocalDateTimeUtils.toStr(dynamicStateStartDateTime, "yyyy-MM"));
                    dynamicStateStartDateTime = dynamicStateStartDateTime.plusMonths(1);
                    break;
                case Year:
                    dateList.add(String.valueOf(dynamicStateStartDateTime.getYear()));
                    dynamicStateStartDateTime = dynamicStateStartDateTime.plusYears(1);
                    break;
                default:
                    break;
            }
        }
        return dateList;
    }

    /**
     * 根据时间获取时间范围
     *
     * @param dateType 时间类型
     */
    private LocalDateTime[] getEnumDimensionTimeInterval(EnumDimension dateType) {
        LocalDateTime curDateTime = LocalDateTime.now();
        LocalDateTime[] timeIntervalTimeArr = new LocalDateTime[2];
        LocalDateTime startDateTime = curDateTime;
        LocalDateTime endDateTime = curDateTime;

        switch (dateType) {
            case Day:
                startDateTime = LocalDateTimeUtils.getDateMonthFirstDay(curDateTime);
                endDateTime = LocalDateTimeUtils.getDateMonthLastDay(curDateTime);
                break;
            case Month:
                startDateTime = LocalDateTimeUtils.getDateYearFirstDay(startDateTime);
                endDateTime = LocalDateTimeUtils.getDateYearLastDay(endDateTime);
                break;
            case Year:
                startDateTime = LocalDateTimeUtils.getDateYearFirstDay(startDateTime);
                int year = curDateTime.getYear() - 2024;
                startDateTime = startDateTime.plusYears(year);
                endDateTime = LocalDateTimeUtils.getDateYearLastDay(endDateTime);
                break;
            default:
                break;
        }
        timeIntervalTimeArr[0] = startDateTime;
        timeIntervalTimeArr[1] = endDateTime;
        return timeIntervalTimeArr;
    }


}
